package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.FileReport;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;

/**
 * Created by Lenovo on 2017/2/28.
 */
public class FileReportDetailFragment extends Fragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.FileReportDetailFragment.EXTRA_CONTENT";
  protected static final String EXTRA_MAINID =
      "com.isunland.managesystem.ui.FileReportDetailFragment.EXTRA_MAINID";
  private final int REQUEST_FILE = 0;

  @BindView(R.id.et_remark) EditText etRemark;
  @BindView(R.id.tv_fileName) TextView tvFileName;
  @BindView(R.id.iv_fileName) ImageView ivFileName;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;

  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private FileReport mContent;
  private String mMainId;
  private String mId;
  private String mFilePath;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    mUser = CurrentUser.newInstance(getActivity());
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
      actionBar.setTitle(R.string.fileReport);
    }
    mMainId = getArguments().getString(EXTRA_MAINID);
    mContent = (FileReport) getArguments().getSerializable(EXTRA_CONTENT);
    if (mContent != null) {
      mId = mContent.getId();
      mFilePath = mContent.getFilePath();
    }
    if (mContent == null) {
      mId = UUID.randomUUID().toString();
      mFilePath = "";
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_file_report, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    if (mContent == null) {
      tvRegStaffName.setText(mUser.getRealName());
      tvRegDate.setText(MyDateUtil.parseDateToString(new Date()));
    }
    if (mContent != null) {
      etRemark.setText(mContent.getRemark());
      tvFileName.setText(mContent.getFileName());
      tvRegStaffName.setText(mContent.getRegStaffName());
      tvRegDate.setText(mContent.getRegDate());
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_save_delete, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_save:
        if (TextUtils.isEmpty(tvFileName.getText().toString())) {
          ToastUtil.show(R.string.chooseExtraFile);
        } else {
          volleyPostSave();
        }
        return true;
      case R.id.menu_item_delete:
        volleyPostDel();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostDel() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_FILE_REPORT_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_FILE_REPORT_SAVE);
    HashMap<String, String> params = new HashMap<>();
    params.put("mainid", mMainId);
    params.put("id", mId);
    params.put("filePath", mFilePath);
    params.put("remark", etRemark.getText().toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  @OnClick({ R.id.tv_fileName, R.id.iv_fileName }) public void onClick(View view) {
    switch (view.getId()) {
      case R.id.tv_fileName:
        if (mContent != null) {
          downFile(mContent.getFilePath());
        }
        break;
      case R.id.iv_fileName:
        chooseFile(REQUEST_FILE);
        break;
    }
  }

  private void downFile(String serverPath) {
    if (!TextUtils.isEmpty(serverPath)) {
      ExtraDownLoadDialogFragment dialog = ExtraDownLoadDialogFragment.newInstance("", serverPath);
      FragmentManager fm = getActivity().getSupportFragmentManager();
      dialog.show(fm, "");
    }
  }

  private void chooseFile(int requestCode) {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        requestCode);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_FILE) {
      //上传附件
      volleyPostExtra(getFile(data));
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleyPostExtra(String resourcefilePath) {
    if (!TextUtils.isEmpty(resourcefilePath)) {
      new FileNetWorkUtil(getActivity()).upLoadFile(resourcefilePath, ApiConst.URL_UPLOAD_FILE,
          "customer.r_complain_fault_file", mId, new myUpLoadHandler(), false);
    }
  }

  private String getFile(Intent data) {
    String path1 = FileUtil.getPath(getActivity(), data.getData());
    File mFile = null;
    if (path1 != null) {
      mFile = new File(path1);
    }
    if (null == mFile) {
      ToastUtil.show(R.string.fileNotFound);
      return "";
    }
    return mFile.getAbsolutePath();
  }

  public static FileReportDetailFragment newInstance(FileReport content, String mainId) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putString(EXTRA_MAINID, mainId);
    FileReportDetailFragment fragment = new FileReportDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  private class myUpLoadHandler extends AsyncHttpResponseHandler {

    public myUpLoadHandler() {
    }

    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      MyUtils.dismissDialog();
      ToastUtil.show(R.string.fileUploadFailure);
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        if (result == null) {
          MyUtils.dismissDialog();
          ToastUtil.show(R.string.wrong_data);
        }
        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          // 上传成功,再上传数据
          ToastUtil.show(R.string.fileUploadSuccess);
          String selcurFile = result.getMessage();
          mFilePath = selcurFile;
          tvFileName.setText(FileUtil.getFileNameByFilePath(selcurFile));
        } else {
          MyUtils.dismissDialog();
          ToastUtil.show(result.getMessage());
        }
      } catch (JsonSyntaxException e) {
        e.printStackTrace();
        ToastUtil.show(R.string.fileUploadFailure);
      } catch (Resources.NotFoundException e) {
        e.printStackTrace();
        ToastUtil.show(R.string.fileUploadFailure);
      }
    }
  }
}
